<template>
  <div class="container">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />
    <van-search
      v-model="keyword"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
    />
    <!-- 输入关键词的时候，联想词列表  猜测用户搜索的内容-->
    <van-cell-group class="suggest-box" v-if="keyword">
      <!-- span高亮联想关键词 -->
      <van-cell
        icon="search"
        @click="onSearch(sug.replace(`<span>${keyword}</span>`, keyword))"
        v-for="sug in suggestList"
        :key="sug"
        ><p v-html="sug"></p
      ></van-cell>
    </van-cell-group>
    <div class="history-box" v-else>
      <div class="head">
        <span>历史记录</span>
        <!-- 删除全部 -->
        <van-icon @click="delAllHistory" name="delete"></van-icon>
      </div>
      <van-cell-group>
        <van-cell v-for="(his, i) in historyList" :key="his">
          <a class="word_btn">{{ his }}</a>
          <!-- 点击删除多个 -->
          <van-icon
            @click="delHistory(i)"
            class="close_btn"
            slot="right-icon"
            name="cross"
          />
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<script>
import { suggest } from '../../api/search'
// 1)存储用户的关键词搜索行为
// 1.设计数据结构=》['1024','小米']字符串
// 2.存储key名
const TT_HS = 'TT_HS'
// localStorage.setItem(TT_HS, JSON.stringify(['123', '小米', '华为']))
export default {
  name: 'search-index',
  data () {
    return {
      keyword: '',
      historyList: JSON.parse(localStorage.getItem(TT_HS)) || [],
      timer: null,
      suggestList: [] // 联想词列表
    }
  },
  watch: {
    // 用户实时输入=》会多次调用接口查找联想词列表（用户还没输入就调用完了）=》1.浪费服务器资源，2.公司成本
    // 实现函数防抖：
    // 1.定义一个存储定时器ID变量
    // 2.在定时器规定时间，如果有重复执行就取消
    keyword () {
      // 在定时器规定时间，如果有重复执行就取消
      this.timer && clearTimeout(this.timer)
      // 2.开启定时器
      this.timer = setTimeout(async () => {
        try {
          // 判断是否为空
          if (!this.keyword) {
            this.suggestList = []
            return
          }
          const { data } = await suggest(this.keyword)
          console.log('联想词：', data)
          if (data.options[0] === null) return
          this.suggestList = data.options.map((word) => word.toLowerCase().replace(this.keyword, `<span>${this.keyword}</span>`))
        } catch (error) {
          console.dir(error)
        }
      }, 600)
    }
  },
  methods: {
    // 搜索事件回调=》手机端软键盘的回车完成
    onSearch (val) {
      console.log(val, this.keyword)
      // 1.存储搜索关键词
      // 2.跳转搜索结果页并携带当前搜索关键词
      if (!val) return
      const historySet = new Set(this.historyList)
      historySet.add(val)
      this.historyList = [...historySet]

      localStorage.setItem(TT_HS, JSON.stringify(this.historyList))
      this.$router.push(`/search/result?q=${val}`)
    },
    delHistory (i) {
      // 1.内存删除
      this.historyList.splice(i, 1)
      // 2.本地删除
      localStorage.setItem(TT_HS, JSON.stringify(this.historyList))
    },
    delAllHistory () {
      this.historyList = []
      localStorage.setItem(TT_HS, JSON.stringify(this.historyList))
    }
    // 删除单个搜索历史记录

  }
}
</script>

<style scoped lang='less'>
.suggest-box {
  /deep/ .van-cell {
    padding: 10px 20px;
    color: #999;
    p {
      span {
        color: red;
      }
    }
  }
}
.history-box {
  padding: 0 20px;
  .head {
    line-height: 36px;
    color: #999;
    text-align: left;
    .van-icon {
      font-size: 16px;
      float: right;
      margin-top: 10px;
    }
  }
  .van-cell {
    padding: 10px 0;
  }
  .word_btn {
    color: #3296fa;
  }
  .close_btn {
    margin-top: 5px;
    color: #999;
  }
}
</style>
